<!-- by 7527189 2 0 -->
<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="18">
              <a-col :md="6" :sm="24">
                <a-form-item label="报价单模板分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select style="width:100%" :dropdownStyle="{maxHeight:'200px',overflow:'auto'}" allow-clear
                                 @select="onCategorySelect"
                                 :treeData="categoryTree" v-model="queryParam.categoryId" placeholder="请选择报价单模板分类">
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="报价单模板" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select placeholder="请选择报价单模板" @select="onQuoteTemplateItemSelect" v-model="selectedQuoteTemplateId" allowClear>
                    <a-select-option v-for="qt in quoteTemplateList" :key="qt.id">
                      {{ qt.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 操作按钮区域 -->

        <!-- 操作按钮区域 -->
        <div class="table-operator"  style="margin-top: 5px">
          <a-button @click="handleAdd" type="primary" icon="plus" >新增</a-button>
        </div>

        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="defColumns"
            :dataSource="dataSource"
            :scroll="scroll"
            :loading="loading"
            @change="handleTableChange">
            <span slot="action" slot-scope="text, record">
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                <a>删除</a>
              </a-popconfirm>
            </span>
          </a-table>
        </div>
        <!-- table区域-end -->
        <!-- 表单区域 -->
      </a-card>
    </a-col>
    <quote-template-item-modal ref="modalForm" @ok="refresh"></quote-template-item-modal>
    <j-select-material-modal ref="materialModal" @ok="onSelectMaterial"></j-select-material-modal>
  </a-row>

</template>
<script>
import ImportFileModal from '@/components/tools/ImportFileModal'
import {  queryQuoteCategoryTreeList } from '@/api/api'
import { getMpListShort } from '@/utils/util'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JEllipsis from '@/components/jeecg/JEllipsis'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
import { deleteAction, getAction, postAction } from '@api/manage'
import QuoteTemplateItemModal from '@views/quote/modules/QuoteTemplateItemModal.vue'
import JSelectMaterialModal from '@comp/jeecgbiz/modal/JSelectMaterialModal.vue'
import MaterialModal from '@views/material/modules/MaterialModal.vue'

export default {
  name: "QuoteTemplateItem",
  mixins:[JeecgListMixin],
  components: {
    MaterialModal,
    JSelectMaterialModal,
    QuoteTemplateItemModal,
    ImportFileModal,
    JEllipsis,
    JDate
  },
  data () {
    return {
      categoryTree:[],
      quoteTemplateId:'',
      quoteTemplateList:[],
      quoteTemplateItems:{},
      quoteTemplateSubSystems:[],
      selectedQuoteTemplateId:'',
      selectedQuoteTemplateSubSystem:'',
      mPropertyListShort: '',
      model: {},
      labelCol: {
        span: 5
      },
      wrapperCol: {
        span: 18,
        offset: 1
      },
      // 查询条件
      queryParam: {

      },
      // 实际表头
      columns:[],
      // 初始化设置的表头
      settingColumns:['fullBarCode','mBarCode','name','mfrs','standard','model','color','categoryName','materialOther','unit', 'stock',
        'otherField1','caizhi','biaozhun','lianjie','paoguangdu','mopian','changdu','otherField2','otherField3','standard',
        'purchaseDecimal','commodityDecimal','wholesaleDecimal','discountRate','taxRate','lowDecimal','enabled','enableSerialNumber','enableBatchNumber','action'],
      // 默认的列
      defColumns: [
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
        // {title: '图片', dataIndex: 'pic', width: 65, scopedSlots: { customRender: 'customPic' }},
        // {title: '子系统', dataIndex: 'subSystem', width: 80},
        {title: '名称', dataIndex: 'materialInfo.name', width: 120, scopedSlots: { customRender: 'customName' } },
        {title: '类别', dataIndex: 'materialInfo.categoryName', width: 100 },
        {title: '数量', dataIndex: 'count', width: 80},
        {title: '单位', dataIndex: 'materialInfo.unit', width: 50 ,
          customRender:function (t,r,index) {
            if (r) {
              let name = t?t:r.unitName
              if(r.sku) {
                return name + '[SKU]';
              } else {
                return name;
              }
            }
          }
        },
        {title: '单价（元）', dataIndex: 'materialInfo.wholesaleDecimal', width: 100},
        // {title: '编码', dataIndex: 'materialInfo.fullBarCode', width: 80},
        // {title: '条码', dataIndex: 'materialInfo.mBarCode', width: 80},
        // {title: '制造商', dataIndex: 'materialInfo.mfrs', width: 120 },
        { title: '规格型号', dataIndex: 'materialInfo.model', width: 120 },
        { title: '尺寸', dataIndex: 'materialInfo.otherField1', width: 80 },
        { title: '材质', dataIndex: 'materialInfo.caizhi' , width: 80},
        { title: '标准', dataIndex: 'materialInfo.biaozhun', width: 80 },
        { title: '连接形式', dataIndex: 'materialInfo.lianjie', width: 80 },
        { title: '抛光要求', dataIndex: 'materialInfo.paoguangdu', width: 80 },
        { title: '密封形式', dataIndex: 'materialInfo.mopian' , width: 80},
        { title: '长度', dataIndex: 'materialInfo.changdu' , width: 80},
        { title: '温度', dataIndex: 'materialInfo.otherField2', width: 80 },
        { title: '压力', dataIndex: 'materialInfo.otherField3' , width: 80},
        { title: '其他技术参数', dataIndex: 'materialInfo.standard', width: 120 },
        // {title: '型号', dataIndex: 'model', width: 120},
        // {title: '其他技术参数', dataIndex: 'standard', width: 120},
        // {title: '颜色', dataIndex: 'color', width: 70 },
        // {title: '扩展信息', dataIndex: 'materialOther', width: 100 },

        // {title: '库存', dataIndex: 'materialInfo.stock', width: 50,
        //   scopedSlots: { customRender: 'customRenderStock' }
        // },
        // {title: '面价', dataIndex: 'wholesaleDecimal', width: 80},
        // {title: '采购单价', dataIndex: 'purchaseDecimal', width: 80},
        // {title: '成本价', dataIndex: 'lowDecimal', width: 80},
        // {title: '仓位货架', dataIndex: 'position', width: 80},
        {title: '备注', dataIndex: 'materialInfo.remark', width: 80},
        {title: '状态', dataIndex: 'enabled', align: "center", width: 60,
          scopedSlots: { customRender: 'customRenderEnabled' }
        }
      ],
      url: {
        list: "/quote/template/item/list?quoteTemplateId="+this.quoteTemplateId,
        delete: "/quote/template/item/delete",
        add: "/quote/template/item/add",
      }
    }
  },
  created() {
    this.model = Object.assign({}, {});
    // this.initColumnsSetting()
    this.loadQuoteTemplateCategoryTreeData();
  },
  computed: {
  },
  methods: {
    loadQuoteTemplateCategoryTreeData(){
      let that = this;
      let params = {};
      params.id='1';
      queryQuoteCategoryTreeList(params).then((res)=>{
        if(res){
          that.categoryTree = [];
          for (let i = 0; i < res.length; i++) {
            let temp = res[i];
            that.categoryTree.push(temp);
          }
        }
      })
    },
    onCategorySelect(quoteCategoryId){
      this.quoteTemplateList = []
      this.quoteTemplateId = ''
      let list_url = "/quote/template/list?quoteCategoryId="+quoteCategoryId;
      getAction(list_url,{}).then(res=>{
        this.quoteTemplateList = res.data.list;
      })
    },
    onQuoteTemplateItemSelect(quoteTemplateId){
      this.quoteTemplateId = quoteTemplateId;
      this.url.list = "/quote/template/item/list?quoteTemplateId="+this.quoteTemplateId
      this.queryQuoteTemplateItemList()
    },
    queryQuoteTemplateItemList() {
      return new Promise((resolve, reject) => {
        getAction(this.url.list, {})
          .then(res => {
            // 更新数据
            this.dataSource = res.data.list;
            resolve(); // 数据加载完成
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    onQuoteTemplateItemSubSystemSelect(subSystem){
      this.changeSubSystemTableData(subSystem)
    },
    changeSubSystemTableData(subSystem){
      this.selectedQuoteTemplateSubSystem = subSystem;
      this.dataSource = this.quoteTemplateItems[subSystem];
    },
    handleEdit: function (record)  {
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "调整数量："+record.materialInfo.name;
      this.$refs.modalForm.disableSubmit = false;
    },
    handleDelete: function (id) {
      if(!this.url.delete){
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      postAction(that.url.delete, {id: id}).then((res) => {
        if(res.code === 200){
          that.refresh();
        } else {
          that.$message.warning(res.data.message);
        }
      });
    },
    handleAdd: function () {
      console.log('handle add',this.selectedQuoteTemplateId)
      if ( this.selectedQuoteTemplateId === ''){
        this.$message.error("请先选择要添加材料的报价单模板")
      }else{
        this.$refs.materialModal.showModal('1')
      }
    },
    onSelectMaterial(selectMaterialRows, selectMaterialIds){
      console.log(selectMaterialRows)
      if ( selectMaterialRows.length > 0 ){
        let that = this;
        let params = {
          materialId:selectMaterialRows[0].id,
          quoteTemplateId:this.selectedQuoteTemplateId
        }
        postAction(this.url.add,params)
          .then(res=>{
            that.refresh();
          })
      }

    },
    refresh() {
      // 显示加载状态
      this.loading = true;
      this.dataSource = []; // 清空现有数据

      // 调用查询方法，并在成功后更新 dataSource
      this.queryQuoteTemplateItemList()
        .then(() => {
          // 更新当前子系统对应的数据
          this.queryQuoteTemplateItemList();
        })
        .finally(() => {
          // 关闭加载状态
          this.loading = false;
        });
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
<style>
.item-img {
  cursor:pointer;
  position: static;
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>